package com.wf.course.service.impl;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.utils.page.PageBean;
import com.wf.course.dao.IGoodsImageMapper;
import com.wf.course.model.goods.GoodsImage;
import com.wf.course.service.IGoodsImageService;
import com.wf.course.web.Constants;
import com.wf.course.web.OSSUtil;

@Service
@Transactional(rollbackFor=Exception.class)
public class IGoodsImageServiceImpl implements IGoodsImageService{
	
	@Autowired
	private IGoodsImageMapper mapper;

	@Override
	public void indexInfo(PageBean<GoodsImage> pageBean) {
		// TODO Auto-generated method stub
		pageBean.setResults(this.mapper.queryList(pageBean));
		pageBean.setTotalCount(this.mapper.getTotalCount(pageBean).intValue());
	}

	@Override
	public void saveOrUpdateGoodsImage(GoodsImage goodsImage,MultipartFile imgFile) {
		// TODO Auto-generated method stub
		if(goodsImage.getId()==null){
			//图片
			if (!imgFile.isEmpty()) {
				String goodsImg = "";
				try {
					goodsImg = OSSUtil.addFile(imgFile, "wf_goods/goodsImg", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				goodsImage.setGoodsImg(goodsImg);
			}
		 
			this.mapper.saveGoodsImage(goodsImage);
		}else{
			
			if (imgFile.getSize() != 0) {
				GoodsImage img = mapper.queryGoodsImageById(goodsImage.getId());
				try{
					if(StringUtils.isNotBlank(img.getGoodsImg())){
						// 删除原来图片
						OSSUtil.delete(img.getGoodsImg(), Constants.IGM_BUCKET);
					}
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
				// 重新上传
				String goodsImg = "";
				try {
					goodsImg = OSSUtil.addFile(imgFile, "wf_goods/goodsImg", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				goodsImage.setGoodsImg(goodsImg);
			}
		 
			this.mapper.updateGoodsImage(goodsImage);
		}
	}
		
		
	@Override
	public GoodsImage queryGoodsImageById(Integer id) {
		// TODO Auto-generated method stub
		return this.mapper.queryGoodsImageById(id);
	}

	@Override
	public void deleteById(Integer id) {
		// TODO Auto-generated method stub
		this.mapper.deleteById(id);
	}

	@Override
	public void deleteByGoodsId(Integer goodsId) {
		// TODO Auto-generated method stub
		this.mapper.deleteByGoodsId(goodsId);
		
	}

 
	
}
